<?php


namespace App\Models\Logs;

use App\Library\ClientIp;
use App\Models\System\User;
use App\Traits\DateTrait;
use Illuminate\Support\Facades\DB;
use Jenssegers\Agent\Agent;
use Illuminate\Database\Eloquent\Model;

class LoginLog extends Model
{
    use DateTrait;
    protected $table = 'users_login_log';
    protected $fillable = ['user_id', 'message', 'platform', 'browser', 'ip', 'ip_address', 'header'];

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    /**
     * @param string $message
     * @param int $uid
     */
    public static function createLoginLog(string $message, int $uid): void
    {
        try {
            DB::transaction(function () use ($message, $uid) {
                $agent = new Agent();
                $ip = getClientIp();
                empty($uid) && $uid = auth('admin')->id();
                static::query()->create([
                    'user_id' => $uid,
                    'message' => trim($message),
                    'platform' => $agent->platform(),
                    'browser' => $agent->browser(),
                    'ip' => $ip,
                    'ip_address' => ClientIp::getLocation($ip)["region"],
                    'header' => json_encode(request()->header()),
                ]);
            });
        }catch (\Exception $e) {
            report($e);
        }
    }
}
